package org.example.netty.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;
import java.security.SecureRandom;

public class NioBufferChannel {
    public static void main(String[]args)throws Exception {
        FileInputStream fileInputStream =new FileInputStream("NioTest2.txt");
        FileChannel fileChannel =fileInputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(512);
        fileChannel.read(byteBuffer);

        byteBuffer.flip();

        while(byteBuffer.remaining()>0){
            byte b=byteBuffer.get();
            System.out.println("Character:"+(char)b);
        }
        fileInputStream.close();
    }
    public static void main1(String[]args)throws Exception {
        FileOutputStream fileOutputStream = new FileOutputStream("NioTest3.txt");
        FileChannel fileChannel = fileOutputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(512);
        byte[] messages = "hello world welcome,nihao".getBytes();
        for (int i = 0; i < messages.length; ++i) {
            byteBuffer.put(messages[i]);
        }
        byteBuffer.flip();
        fileChannel.write(byteBuffer);
        fileOutputStream.close();
    }
    public static void main2(String[] args){
        IntBuffer buffer =IntBuffer.allocate(10);
        for(int i=0;i<buffer.capacity();++i){
            int randomNumber =new SecureRandom().nextInt(20);
            buffer.put(randomNumber);
        }
        buffer.flip();
        while(buffer.hasRemaining()){
            System.out.println(buffer.get());
        }
    }

}
